package com.cjhedu.web.filter;


import com.alibaba.fastjson.JSONObject;
import com.cjhedu.web.utils.MyJwtUtils;
import com.cjhedu.web.utils.MyResponseResult;
import com.cjhedu.web.utils.MyThreadLocalUtils;
import com.cjhedu.web.utils.Result;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author 陈佳豪
 * @version 1.0
 */
//@WebFilter(urlPatterns = "/*")
//@Component
public class MyLoginFilter implements Filter {
    //@Autowired
    private MyJwtUtils myJwtUtils;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("==================================");
        //1.获取用户请求路径，去的路直接放行
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        //获取资源路径
        String uri = request.getRequestURI();
        if ("/login".equals(uri)){
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //StringBuffer requestURL = request.getRequestURL();


        //2.根据请求头校验 Token获取令牌
        String token = request.getHeader("Token");
        // 示例：从请求头获取 Token（假设使用 "Authorization: Bearer <token>" 格式）

        //if (token == null || !token.startsWith("Bearer ")) {
        //    // 处理未授权请求：返回 401 或跳转到登录页
        //    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        //    response.getWriter().write("缺少有效的 JWT 令牌");
        //    return; // 终止过滤器链
        //}
        //3.校验令牌是否合法  合法放行
        Map<String, Object> map = myJwtUtils.jieXiJwt(token);
        if (map == null){
            //说明令牌过期或者不合法，直接响应一个信息
            System.out.println("不合法的情况~~~");
            MyResponseResult<Object> result = MyResponseResult.error("NULL");
            String jsonString = JSONObject.toJSONString(result);
            //HttpServletResponse response = (HttpServletResponse)servletResponse;
            response.getWriter().println(jsonString);
            return;
        }
        //合法情况 保存变量 以便后续使用
        MyThreadLocalUtils.setValue(map);
        //4.不合法 响应一个错误状态对象
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
